package cn.com.chengmandian.core.web.utils;

import cn.com.chengmandian.core.common.enums.ClientsEnum;
import cn.com.chengmandian.core.web.constants.TokenAttrEnum;
import cn.com.chengmandian.core.web.pojo.LoginUser;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWTUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TokenUtil {
    private LoginUser loginUser;

    private ClientsEnum clientsEnum;

    private Map<String, Object> attrs;

    public TokenUtil(LoginUser loginUser, ClientsEnum clientsEnum) {
        this.loginUser = loginUser;
        this.clientsEnum = clientsEnum;
    }

    public static TokenUtil create(LoginUser loginUser, ClientsEnum clientsEnum) {
        return new TokenUtil(loginUser, clientsEnum);
    }

    public TokenUtil setAttr(String key, Object value) {
        if (this.attrs == null) this.attrs = new HashMap<>();
        this.attrs.put(key, value);
        return this;
    }

    public TokenUtil setMerchantsId(Integer merchantsId) {
        setAttr(TokenAttrEnum.MID.getCode(), merchantsId);
        return this;
    }

    public TokenUtil setWarehouses(List<Integer> warehouses) {
        setAttr(TokenAttrEnum.WHS.getCode(), warehouses);
        return this;
    }

    public TokenUtil setShops(List<Integer> shops) {
        setAttr(TokenAttrEnum.SPS.getCode(), shops);
        return this;
    }

    public String build() {
        loginUser.setAttrs(attrs);
        loginUser.setExpireDate(DateUtil.offsetDay(DateUtil.date(), clientsEnum.getExpireDay()).getTime());

        // 设置头部信息
        Map<String, Object> headers = new HashMap<>(2);
        headers.put("Type", "Jwt");
        headers.put("alg", "HS256");
        return JWTUtil.createToken(headers, BeanUtil.beanToMap(loginUser), clientsEnum.getSecret().getBytes());
    }
}
